<template>
  <div class="page">

    <!-- 累计数据 开始 -->
    <div class="today_info">
      <div class="hospital_name">{{hospitalName}}</div>
      <div class="title">
        <div class="left">
          <!-- <span class="hospital_name">{{hospitalName}}</span> -->
          <span>累计数据</span>
          <span class="time">更新时间：{{updateTime}}</span>
        </div>
        <div class="right">
          <!-- <el-button type="primary" size="small" plain icon="el-icon-upload2">导出</el-button> -->
          <el-date-picker v-model="staticTime" size="mini" type="daterange" class="range_time" @change="changeStaticTime" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </div>
      </div>
      <div class="cell_list">
        <div class="cell" v-for="(item, index) in todayList" :key="`idx_${index}`">
          <div class="h1">{{ item.name }}</div>
          <div class="h2">
            {{ item.num?item.num.toFixed(0):0}}
            {{item.id == 'appointmentArrivedRate' || item.id == 'arrivedDealRate'?'%':''}}
            <i :class="`el-icon-caret-${
                item.status == 1 ? 'bottom cgreen' : 'top cred'
              }`" v-if="item.status"></i>
          </div>
        </div>
      </div>
    </div>
    <!-- 累计数据 end -->

    <!-- 近三个月成交情况、成交客单价分布 开始 -->
    <div class="row_box">
      <div class="row_left">
        <div class="head">
          <span class="name">近三个月成交情况</span>
        </div>

        <!-- 图表区域 开始 -->
        <div class="chart_box">
          <div class="chart" id="dealChart"></div>
        </div>
        <!-- 图表区域 end -->

      </div>
      <div class="row_right">
        <div class="head"><span class="name">成交客单价分布</span></div>
        <div class="pie_chart" id="dealPie"></div>
      </div>
    </div>
    <!-- 近三个月成交情况、成交客单价分布 开始 -->

    <!-- 业务分析 开始 -->
    <div class="row_box">
      <div class="row_left">
        <div class="head">
          <span class="name">业务分析</span>
          <el-date-picker v-model="rangeTime" size="mini" class="range_time" type="daterange" @change="changeTime" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </div>

        <!-- 图表区域 开始 -->
        <div class="chart_box">
          <div class="chart" id="analysisChart"></div>
        </div>
        <!-- 图表区域 end -->

        <!-- 详情 开始 -->
        <div class="analysis_list">
          <div class="cell">
            <div class="h1">总成交</div>
            <div class="h2">{{staticInfo.totalDealAmount?Number(staticInfo.totalDealAmount).toFixed(0):0}}</div>
          </div>
          <div class="cell">
            <div class="h1">总收款</div>
            <div class="h2">{{staticInfo.totalCollectMoney?staticInfo.totalCollectMoney.toFixed(0):0}}</div>
          </div>
          <div class="cell">
            <div class="h1">收款率</div>
            <div class="h2">{{staticInfo.collectRate?staticInfo.collectRate.toFixed(0):0}}% <i :class="staticInfo.collectRate>staticInfo.averageCollectRate?'el-icon-caret-top':'el-icon-caret-bottom'"></i><span>{{showNumber(staticInfo.collectRate,staticInfo.averageCollectRate)}}</span></div>
          </div>
          <div class="cell">
            <div class="h1">到店率</div>
            <div class="h2">{{staticInfo.arrivedRate?staticInfo.arrivedRate.toFixed(0):0}}%<i :class="staticInfo.arrivedRate>staticInfo.averageArrivedRate?'el-icon-caret-top':'el-icon-caret-bottom'"></i><span>{{showNumber(staticInfo.arrivedRate,staticInfo.averageArrivedRate)}}</span></div>
          </div>
          <div class="cell">
            <div class="h1">到店成交率</div>
            <div class="h2">{{staticInfo.arrivedDealRate?staticInfo.arrivedDealRate.toFixed(0):0}}%<i :class="staticInfo.arrivedDealRate>staticInfo.averageArrivedDealRate?'el-icon-caret-top':'el-icon-caret-bottom'"></i><span>{{showNumber(staticInfo.arrivedDealRate,staticInfo.averageArrivedDealRate)}}</span></div>
          </div>
          <div class="cell">
            <div class="h1">种植和矫正成交率</div>
            <div class="h2">{{staticInfo.mainDemandsDealRate?staticInfo.mainDemandsDealRate.toFixed(0):0}}%<i :class="staticInfo.mainDemandsDealRate>staticInfo.averageMainDemandsDealRate?'el-icon-caret-top':'el-icon-caret-bottom'"></i><span>{{showNumber(staticInfo.mainDemandsDealRate,staticInfo.averageMainDemandsDealRate)}}</span></div>
          </div>
          <div class="cell">
            <div class="h1">客单价</div>
            <div class="h2">{{staticInfo.customerUnitPrice?staticInfo.customerUnitPrice.toFixed(0):0}}<i :class="staticInfo.customerUnitPrice>staticInfo.averageCustomerUnitPrice?'el-icon-caret-top':'el-icon-caret-bottom'"></i><span>{{showNumber(staticInfo.customerUnitPrice,staticInfo.averageCustomerUnitPrice,true)}}</span></div>
          </div>
          <div class="cell">
            <div class="h1">种植客单价</div>
            <div class="h2">{{staticInfo.plantCustomerUnitPrice?staticInfo.plantCustomerUnitPrice.toFixed(0):0}}<i :class="staticInfo.plantCustomerUnitPrice>staticInfo.averagePlantCustomerUnitPrice?'el-icon-caret-top':'el-icon-caret-bottom'"></i><span>{{showNumber(staticInfo.plantCustomerUnitPrice,staticInfo.averagePlantCustomerUnitPrice,true)}}</span></div>
          </div>
          <div class="cell">
            <div class="h1">矫正客单价</div>
            <div class="h2">{{staticInfo.correctCustomerUnitPrice?staticInfo.correctCustomerUnitPrice.toFixed(0):0}}<i :class="staticInfo.correctCustomerUnitPrice>staticInfo.averageCorrectCustomerUnitPrice?'el-icon-caret-top':'el-icon-caret-bottom'"></i><span>{{showNumber(staticInfo.correctCustomerUnitPrice,staticInfo.averageCorrectCustomerUnitPrice,true)}}</span></div>
          </div>
        </div>
        <!-- 详情 end -->

      </div>

      <div class="row_right special_row_right">

        <div class="top_box">
          <div class="head"><span class="name">成交项目分布</span></div>
          <div class="pie_chart" id="dealProjectPie"></div>
        </div>

        <div class="bottom_box">
          <div class="head"><span class="name">成交客户年龄分布</span></div>
          <div class="pie_chart" id="dealAgePie"></div>
        </div>

      </div>

    </div>
    <!-- 业务分析 end -->

    <!-- 预约情况 开始 -->
    <div class="panel_box">
      <div class="head">
        <span class="name">预约情况</span>
      </div>
      <div class="calendar_header">
        <el-date-picker v-model="yearMonth" type="month" placeholder="选择年月" value-format="yyyy-MM" size="small" @change="getList">
        </el-date-picker>
        <div class="example_list">
          <span class="cspan c_white"></span>
          <span>待到店</span>
          <span class="cspan c_grey"></span>
          <span>已取消</span>
          <span class="cspan c_blue"></span>
          <span>已改约</span>
          <span class="cspan c_green"></span>
          <span>已成交</span>
          <span class="cspan c_red"></span>
          <span>未成交</span>
        </div>
      </div>
      <el-calendar class="el_calendar" v-model="yearMonth">
        <template slot="dateCell" slot-scope="{data}">
          <p class="p_today" :class="data.isSelected ? 'is-selected' : ''" style="text-align:left">
            {{ data.day.split('-').slice(2).join('-') }}
          </p>
          <el-popover placement="right" width="800" trigger="hover">
            <div>
              <div class="title">{{data.day}}</div>
              <div class="popover_box">
                <p v-for="(item,index) in getData(data)" :key="index">
                  <span class="el_tag" :class="classNameList[item.status]">{{item.name}}/{{showTime(item.appointmentTime)}}/{{item.enrollProjectNames}}/{{item.principal}}/{{item.hospitalName}}</span>
                </p>
              </div>
            </div>
            <div class="note_list" slot="reference">
              <template v-for="(item,index) in getData(data)">
                <p :key="index" v-if="index<6">
                  <span class="el_tag" :class="classNameList[item.status]" @click="lookUser(item)">{{item.name}}/{{showTime(item.appointmentTime)}}/{{item.enrollProjectNames}}/{{item.principal}}/{{item.hospitalName}}</span>
                </p>
              </template>
            </div>
          </el-popover>
        </template>
      </el-calendar>
    </div>
    <!-- 预约情况 end -->

  </div>
</template>
<script>
import * as echarts from "echarts";
import { GETSCHEDULINGSCHEDULES } from "@/http/system";
import {
  GETHOSPITALCUMULATIVE,
  GETHOSPITALDEALLASTTHREEMONTH,
  GETHOSPITALDEALCUSTOMERUNITPRICE,
  GETHOSPITALBUSINESSANALYSISCHART,
  GETHOSPITALDEALPROJECT,
  GETHOSPITALDEALAGE,
  GETHOSPITALBUSINESSANALYSIS,
} from "@/http/hospital";
import moment from "moment";
import { ECHARTCOLOR } from "@/common/constants";
export default {
  data() {
    return {
      todayList: [
        { name: "预约客户数", num: 32, id: "appointmentCnt" },
        { name: "到店客户数", num: 7, id: "arrivedCnt" },
        { name: "成交客户数", num: 7, id: "arrivedDealCnt" },
        { name: "总成交金额", num: 7, id: "totalDealAmount" },
        { name: "总收款金额", num: 7333, id: "totalCollectMoney" },
        { name: "平均客单价", num: 7333, id: "averageCustomerUnitPrice" },
        { name: "预约到店率", num: -100, id: "appointmentArrivedRate" },
        { name: "到店成交率", num: 8999, id: "arrivedDealRate" },
      ],
      updateTime: "",
      yearMonth: moment().format("yyyy-MM"),
      scheduList: [],
      totalInfo: {},
      chartColor: ECHARTCOLOR,
      classNameList: {
        5: "el_tag_white",
        6: "el_tag_grey",
        4: "el_tag_blue",
        8: "el_tag_green",
        7: "el_tag_red",
      },
      staticInfo: {},
      rangeTime: [],
      staticTime: [],
      hospitalName:''
    };
  },
  mounted() {
    this.updateTime = moment().format("yyyy-MM-DD HH:mm:ss");
    this.hospitalName = this.$route.query.name
    this.getList();

    // 获取业务分析
    this.getStatic();

    this.getCumulative();
    this.getThreeDeal();

    this.getDealPrice();
    this.getAnalysis();

    this.getDealProject();
    this.getDealAge();
  },
  methods: {
    // 生成图表
    initChart(id, options) {
      var chartDom = document.getElementById(id);
      var myChart = echarts.init(chartDom);
      myChart.setOption(options);
    },

    // 生成折线图、柱状图图表
    initDealChart(oParams, id) {
      let option = {
        tooltip: {
          trigger: "axis",
          formatter: "{a0}: {c0}<br />{a1}: {c1}<br />{a2}: {c2}%",
        },
        legend: {
          right: "16px",
          data: oParams.legend,
        },
        grid: {
          left: "16",
          right: "26",
          bottom: "16",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: oParams.xaxis,
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        color: this.chartColor,
        series: oParams.series,
      };
      //this.initChart("dealChart", option);
      this.initChart(id, option);
    },

    // 生成饼图
    initPieChart(oParams, id) {
      console.log(oParams);
      let options = {
        tooltip: {
          trigger: "item",
          formatter: "{b0}: {c0}%",
        },
        legend: {
          // orient: "horizontal",
          // right: "0",
          // top: "middle",
        },
        series: [
          {
            type: "pie",
            radius: oParams.radius || "50%",
            label: {
              normal: {
                position: "inside",
                show: true,
                formatter: "{c0}%",
              },
            },
            data: oParams.data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
        color: this.chartColor,
      };
      this.initChart(id, options);
    },

    // 处理折线图数据
    initChartData(obj, type) {
      if (!obj) {
        return "";
      }
      let options = {};
      let _names = [];
      let _arr = [];
      obj.series.map((k) => {
        let m = [];
        let o = {
          type: type || "line",
          smooth: true,
          areaStyle: {},
          emphasis: {
            focus: "series",
          },
        };
        k.data.map((j) => {
          j = j ? Number(j.toFixed(0)) : j;
          m.push(j);
        });
        o.name = k.name;
        o.data = m;
        if (obj.barwidth) {
          o.barwidth = obj.barwidth;
        }
        _arr.push(o);
        _names.push(k.name);
      });

      options.legend = _names;
      options.series = _arr;
      options.xaxis = obj.xaxis;
      return options;
    },

    // 处理饼图数据
    initPieData(obj) {
      let n = obj.series || [];
      let m = obj.xaxis || [];
      let arr = [];
      let options = {};
      let nm = n[0] ? n[0].data : [];
      for (var i = 0; i < m.length; i++) {
        let b = {};
        b.name = m[i];
        b.value = nm[i] ? Number(nm[i]).toFixed(0) : 0;
        arr.push(b);
      }
      options.data = arr;
      console.log(options);
      return options;
    },

    // 展示数据
    getData(obj) {
      let list = this.scheduList;
      return list[obj.day];
    },

    // 展示time
    showTime(str) {
      if (!str) {
        return "";
      }
      let m = moment(str).format("H:mm");
      return m;
    },

    // 获取排班信息
    getList() {
      let _this = this;
      let oParams = {};
      oParams.hospital = this.$route.query.hospital;
      oParams.yearMonth = this.yearMonth;
      GETSCHEDULINGSCHEDULES(oParams).then((res) => {
        let obj = res.data || [];
        let options = {};
        obj.map((k) => {
          let i = moment(k.appointmentTime).format("yyyy-MM-DD");
          if (options[i]) {
            options[i].push(k);
          } else {
            options[i] = [k];
          }
        });
        console.log(options);
        _this.scheduList = options;
      });
    },

    // 获取累计数据
    getCumulative() {
      let n = this.staticTime || []
      let oParams = {};
      oParams.hospitalId = this.$route.query.hospital;
      if(n && n.length>0){
        oParams.startTime = n[0]
        oParams.endTime = n[1]
      }
      GETHOSPITALCUMULATIVE(oParams).then((res) => {
        let obj = res.data || {};
        this.todayList.map((k) => {
          k.num = obj[k.id];
        });
      });
    },

    // 获取最近三个月成交情况
    getThreeDeal() {
      let _this = this;
      let oParams = {};
      oParams.hospitalId = this.$route.query.hospital;
      GETHOSPITALDEALLASTTHREEMONTH(oParams).then((res) => {
        let obj = res.data;
        let options = _this.initChartData(obj);
        _this.initDealChart(options, "dealChart");
      });
    },

    // 获取成交客单价分布
    getDealPrice() {
      let _this = this;
      let oParams = {};
      oParams.hospitalId = this.$route.query.hospital;
      GETHOSPITALDEALCUSTOMERUNITPRICE(oParams).then((res) => {
        let obj = res.data;
        let options = _this.initPieData(obj);
        _this.initPieChart(options, "dealPie");
      });
    },

    // 获取业务分析
    getAnalysis() {
      let _this = this;
      let n = this.rangeTime;
      let oParams = {};
      oParams.hospitalId = this.$route.query.hospital;
      if (n && n.length > 0) {
        oParams.beginDate = n[0];
        oParams.endDate = n[1];
      }
      GETHOSPITALBUSINESSANALYSISCHART(oParams).then((res) => {
        let obj = res.data;
        let list = obj.series;
        let arr = [];

        list.map((k) => {
          let o = {};
          o.name = k.name;
          o.type = "bar";
          o.stack = "total";
          o.label = { show: true };
          o.emphasis = { focus: "series" };
          o.data = k.data.reverse();
          arr.push(o);
        });

        let options = {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          legend: {},
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
          },
          yAxis: {
            type: "category",
            data: ["总成交", "总到店", "总预约"],
          },
          series: arr,
          color: this.chartColor,
        };
        this.initChart("analysisChart", options);
      });
    },

    // 获取项目分布
    getDealProject() {
      let _this = this;
      let oParams = {};
      oParams.hospitalId = this.$route.query.hospital;
      GETHOSPITALDEALPROJECT(oParams).then((res) => {
        let obj = res.data;
        let options = _this.initPieData(obj);
        _this.initPieChart(options, "dealProjectPie");
      });
    },

    // 获取年龄分布
    getDealAge() {
      let _this = this;
      let oParams = {};
      oParams.hospitalId = this.$route.query.hospital;
      GETHOSPITALDEALAGE(oParams).then((res) => {
        let obj = res.data;
        let options = _this.initPieData(obj);
        _this.initPieChart(options, "dealAgePie");
      });
    },

    // 获取业务分析
    getStatic() {
      let _this = this;
      let oParams = {};
      let n = this.rangeTime;
      oParams.hospitalId = this.$route.query.hospital;
      if (n && n.length > 0) {
        oParams.beginDate = n[0];
        oParams.endDate = n[1];
      }

      GETHOSPITALBUSINESSANALYSIS(oParams).then((res) => {
        _this.staticInfo = res.data || {};
      });
    },

    // 计算高于还是低于
    showNumber(max, min, rate) {
      let msg = "高于";
      let o = max - min;
      if (max - min < 0) {
        msg = "低于";
        o = min - max;
      }

      o = Number(o.toFixed(0));
      if (rate) {
        o = Number(((o / min) * 100).toFixed(0));
      }
      return `${msg}平均${o}%`;
    },

    // 切换时间-查询业务分析
    changeTime() {
      this.getStatic();
      this.getAnalysis();
    },

    // 切换时间-查询累计数据
    changeStaticTime(){
      this.getCumulative()
    }

  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/style/static.scss";
.range_time {
  width: 240px;
}
</style>
